<script>
import { ref, onMounted, watch, nextTick } from 'vue';
import * as echarts from 'echarts';
import { ElTabs, ElTabPane } from 'element-plus';
import { searchKeywordDayToMonthTrendService } from '../api/keyword';

export default {
    components: {
        ElTabs,
        ElTabPane
    },
    setup() {
        const activeTab = ref('day');  // 默认选择 'day' 标签
        const chartData = ref({  // 存储请求回来的数据
            day: [],
            week: [],
            month: []
        });
        const chartInstance = ref(null);  // 用于存储图表实例

        // 初始化图表
        const initChart = (containerId, data) => {
            const chart = echarts.init(document.getElementById(containerId));
            const words = data.map(item => item.word);
            const counts = data.map(item => item.count);

            const option = {
                tooltip: { trigger: 'item' },
                xAxis: {
                    type: 'category',
                    data: words,
                    axisLabel: {
                        formatter: function(value) {
                            const maxLength = 9;  // 设置最大字符长度
                            if (value.length > maxLength) {
                                return value.slice(0, maxLength) + '\n' + value.slice(maxLength);
                            }
                            return value;
                        },
                        rotate: 0,
                        interval: 0
                    }
                },
                yAxis: { type: 'value' },
                series: [{
                    data: counts,
                    type: 'bar',
                    barWidth: '50%',
                    barMaxWidth: 50
                }]
            };

            chart.setOption(option);
            chart.resize();  // 确保图表适应容器大小
            chartInstance.value = chart;  // 保存 chart 实例
        };

        // 获取当前选中的 tab 数据
        const getCurrentTabData = (tab) => {
            return chartData.value[tab] || [];
        };

        // 请求数据并更新 chartData
        const fetchChartData = async () => {
            try {
                const response = await searchKeywordDayToMonthTrendService();
                // 假设返回的数据结构包含 day, week, month 的数据
                chartData.value = {
                    day: response.data.day || [],
                    week: response.data.week || [],
                    month: response.data.month || []
                };
                console.log(response.data);  // 调试输出
            } catch (error) {
                console.error('Error fetching chart data:', error);
            }
        };

        // 在组件挂载时获取数据并初始化图表
        onMounted(async () => {
            await fetchChartData();  // 获取数据
            nextTick(() => {  // 使用 nextTick 确保 DOM 渲染完成后再初始化图表
                const initialData = getCurrentTabData(activeTab.value);
                initChart(`${activeTab.value}-chart`, initialData);
            });
        });

        // 监听 tab 变化，更新图表
        watch(activeTab, (newTab) => {
            nextTick(() => {
                const currentTabData = getCurrentTabData(newTab);
                if (chartInstance.value) {
                    chartInstance.value.dispose();  // 销毁当前图表实例
                    chartInstance.value = null;  // 清空 chartInstance 实例
                }
                // 重新初始化图表
                initChart(`${newTab}-chart`, currentTabData);
            });
        });

        return {
            activeTab,
            chartData
        };
    }
};
</script>
<template>
    <div>
        <h1></h1>
    </div>
    <div class="main-1">
        <el-card style="max-width: 80vw">
            <!-- 日、周、月标签 -->
            <el-tabs v-model="activeTab" class="HotelTab">
                <el-tab-pane  name="day">
                    <template #label>
                        <span class="my-label">日</span>
                    </template>
                    <div id="day-chart" style="height: 400px;"></div>
                </el-tab-pane>
                <el-tab-pane  name="week">
                    <template #label>
                        <span class="my-label">周</span>
                    </template>
                    <div id="week-chart" style="height: 400px;"></div>
                </el-tab-pane>
                <el-tab-pane  name="month">
                    <template #label>
                        <span class="my-label">月</span>
                    </template>
                    <div id="month-chart" style="height: 400px;"></div>
                </el-tab-pane>
            </el-tabs>
        </el-card>
    </div>
</template>

<style scoped>
.main-1 {
    width: 80vw;
    margin-left: 10vw;
}
.my-label {
    padding-left: 0px;
	line-height: 100px;
	font-size: 25px;
	font-weight: 100;
    text-align: center;
	font-family: 'Microsoft JhengHei UI Light';
	margin-top: -5px;
    width: 350px;
	color: #D7DCE1;
	letter-spacing: -2px;
	/* 调整标签之间的间距 */
}
::v-deep .el-tabs__item.is-active .my-label {
	color: black !important;
	/* 点击后的颜色 */
}

#day-chart,
#week-chart,
#month-chart {
    width: 100%;
    height: 400px;
}
</style>
